package lt.marsrutai.mobile.android.preference;

import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;

/**
 * <p>Preference which stores it's values as integers.</p>
 * <p><code>android:numeric</code> still needs to be provided with an appropriate value.</p>
 * 
 * @author Justas
 *
 */
public class EditIntegerPreference extends EditTextPreference {

    public EditIntegerPreference(Context context) {
        super(context);
    }

    public EditIntegerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditIntegerPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        if (restoreValue) {
            getEditText().setText(getText());
        }
        else {
            super.onSetInitialValue(restoreValue, defaultValue);
        }
    }
    
    @Override
    protected boolean callChangeListener(Object newValue) {
        return super.callChangeListener(Integer.parseInt((String) newValue));
    }

    @Override
    public String getText() {
        return String.valueOf(getSharedPreferences().getInt(getKey(), 0));
    }

    @Override
    public void setText(String text) {
        getSharedPreferences().edit().putInt(getKey(), Integer.parseInt(text)).commit();
    }
}
